package service

import (
	"errors"
	"framework-server/global"
	"framework-server/model"
	"framework-server/model/request"
	"fmt"
	"gorm.io/gorm"
	"strings"
)

func GetSysObjList(info request.GetSysObjListRequest) (err error, list interface{}, total int64) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	db := global.GVA_DB.Model(&model.SysObj{})
	var ObjList []model.SysObj

	if info.Key != "" {
		db = db.Where("`key` LIKE ?", "%"+info.Key+"%")
	}

	err = db.Count(&total).Error

	if err != nil {
		return err, ObjList, total
	} else {
		db = db.Limit(limit).Offset(offset)
		err = db.Find(&ObjList).Error
	}
	return err, ObjList, total
}


func GetSysObj(Id uint) (err error, sysObj model.SysObj) {
	err = global.GVA_DB.Where("id = ?", Id).First(&sysObj).Error
	return
}

func CreateSysObj(info model.SysObj) (err error) {
	if !errors.Is(global.GVA_DB.Where("`key` = ?", info.Key).First(&info).Error, gorm.ErrRecordNotFound){
		return errors.New("存在相同按钮名")
	}
	return global.GVA_DB.Create(&info).Error
}


func UpdateSysObj(info model.SysObj) (err error) {
	var sysObjs []model.SysObj
	err = global.GVA_DB.Where("`key`=? and id != ?", info.Key, info.ID).Find(&sysObjs).Error
	if (err != nil ){
		return
	}
	if (len(sysObjs) != 0){
		err = errors.New("key已经存在")
		return err
	}
	//获取当前老的obj
	var oldObj model.SysObj
	err = global.GVA_DB.Where("id = ?", info.ID).First(&oldObj).Error
	if (err != nil ){
		return
	}


	tx := global.GVA_DB.Begin() // 开始事务

	if err = tx.Save(&info).Error; err != nil{
		return
	}


	if oldObj.Key != info.Key {
		if err = tx.Table("sys_authority_obj").Where("`key` = ?", oldObj.Key).Updates(map[string]interface{}{
			"key": info.Key,
		}).Error; err != nil {
			tx.Rollback()
			return
		}
	}

	return tx.Commit().Error
}

func DeleteSysObj(info model.SysObj) (err error) {
	err = global.GVA_DB.Delete(info).Error
	return err
}


func GetAllObjs(info request.GetAllObjsRequest) (err error, objs []model.SysObj) {
	err = global.GVA_DB.Find(&objs).Error
	if err != nil{
		return err, objs
	}
	if info.ParentId != "0"{
		var sysAuthorityObjs []model.SysAuthorityObj
		err = global.GVA_DB.Where("authority_id = ?", info.ParentId).Find(&sysAuthorityObjs).Error
		if err != nil{
			return err, objs
		}
		var objMap = make(map[string]model.SysAuthorityObj)
		for _, v := range sysAuthorityObjs{
			objMap[v.Key] = v
		}
		var newObjs = []model.SysObj{}
		for _, v := range objs{
			if objObj, ok := objMap[v.Key]; ok{
				v.ValueList = strings.Split(objObj.Value, ";")
			}else{
				v.ValueList = strings.Split(v.Value, ";")
			}
			newObjs = append(newObjs, v)
		}


		return err, newObjs

	}else{
		var newObjs = []model.SysObj{}
		for _, v := range objs{
			v.ValueList = strings.Split(v.Value, ";")
			newObjs = append(newObjs, v)
		}
		return nil, newObjs
	}
	return nil, objs
}

func GetObjByAutorityId(authorityId string)(err error, objs []model.SysObj) {
	err = global.GVA_DB.Find(&objs).Error
	if err != nil{
		return err, objs
	}
	var sysAuthorityObjs []model.SysAuthorityObj
	err = global.GVA_DB.Where("authority_id = ?", authorityId).Find(&sysAuthorityObjs).Error

	if err != nil{
		return err, objs
	}

	var objMap = make(map[string]model.SysAuthorityObj)
	for _, v := range sysAuthorityObjs{
		objMap[v.Key] = v
	}
	var newObjs = []model.SysObj{}
	for _, v := range objs{
		if objObj, ok := objMap[v.Key]; ok{
			v.ValueList = strings.Split(objObj.Value, ";")
		}else{
			v.ValueList = []string{}
		}
		newObjs = append(newObjs, v)
	}

	return nil, newObjs
}


func AddObjAuthority(info request.AddObjAuthorityRequest)(err error){
	var oldObjs []model.SysAuthorityObj
	fmt.Println(1111, info.ObjMap)

	err = global.GVA_DB.Where("authority_id = ?", info.AuthorityId).Find(&oldObjs).Error
	if err != nil{
		return
	}
	var oldObjMap = make(map[string]model.SysAuthorityObj)
	for _, v:= range oldObjs{
		oldObjMap[v.Key] = v
	}

	for k ,v := range info.ObjMap{
		v.Value = strings.Join(v.ValueList, ";")
		if oldObj, exist := oldObjMap[k]; exist{  //更新对象
			oldObj.Value = v.Value
			err = global.GVA_DB.Save(&oldObj).Error
			if err != nil{
				return
			}
		}else{		//创建对象
			err = global.GVA_DB.Create(&model.SysAuthorityObj{
				AuthorityId: info.AuthorityId,
				Key: k,
				Value: v.Value,
			}).Error
			if err != nil{
				return
			}
		}
	}

	//删除老的对象

	for k ,v := range oldObjMap{
		if _, exist := info.ObjMap[k]; !exist{
			err = global.GVA_DB.Delete(&v).Error
			if err != nil{
				return
			}
		}
	}
	return
}

func GetSysObjMap()(err error, objMap map[string][]string){
	var objs []model.SysObj
	err = global.GVA_DB.Find(&objs).Error
	if err != nil{
		return
	}
	objMap = make(map[string][]string)
	for _,v := range objs{
		objMap[v.Key] = strings.Split(v.Value, ";")
	}
	return
}